package com.lyy.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lyy.Vo.UserLogin;
import com.lyy.system.entity.LoginLog;
import com.lyy.system.mapper.LoginLogMapper;
import com.lyy.system.service.LoginLogService;
import com.lyy.utils.AddressUtil;
import com.lyy.utils.IPUtil;
import com.lyy.utils.RedisUtil;
import eu.bitwalker.useragentutils.Browser;
import eu.bitwalker.useragentutils.OperatingSystem;
import eu.bitwalker.useragentutils.UserAgent;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

@Service
public class LoginLogServiceImpl extends ServiceImpl<LoginLogMapper, LoginLog> implements LoginLogService {

    @Autowired
    private LoginLogMapper loginLogMapper;

    @Autowired
    private RedisUtil redisUtil;

    /**
     * 插入登录日志
     * @param request
     */
    @Override
    public void add(HttpServletRequest request, String token) {
        loginLogMapper.insert(createLoginLog(request,token));
    }


    /**
     * 分页查询登录日志列表
     * @param page
     * @param wrapper
     * @return
     */
    @Override
    public IPage<LoginLog> findLoginlogList(Page<LoginLog> page, QueryWrapper<LoginLog> wrapper) {
        return this.baseMapper.findLoginlogList(page,wrapper);
    }

    /**
     * 删除登录日志
     * @param id
     */
    @Override
    public void deleteById(Long id) {
        this.baseMapper.deleteById(id);
    }

    /**
     *创建登录日志
     * @param request
     * @return
     */
    public  LoginLog createLoginLog(HttpServletRequest request,String token){
        LoginLog loginLog=new LoginLog();
        //获取客户端操作系统
        UserAgent userAgent= UserAgent.parseUserAgentString(request.getHeader("User-Agent"));
        Browser  browser =userAgent.getBrowser();
        OperatingSystem os=userAgent.getOperatingSystem();
        loginLog.setIp(IPUtil.getIpAddr(request));
        loginLog.setLocation(AddressUtil.getCityInfo(IPUtil.getIpAddr(request)));
        loginLog.setUserBrowser(browser.getName());
        loginLog.setUserSystem(os.getName());
        loginLog.setLoginTime(new Date());
        loginLog.setUsername((String) redisUtil.get(token));
        return loginLog;
    }
}
